﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Blog.DTO.BlogMenu;
using AnQinFrameWorkAPI.Entity.Blog.Entity;
using AnQinFrameWorkAPI.Entity.Blog.View.BlogMenu;
using AutoMapper;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.Blog;

public class BlogMenuService
{
    // 数据库上下文
    private readonly DatabaseContext _context;

    // 自动映射器
    private readonly IMapper _mapper;

    // 构造函数注入
    public BlogMenuService(DatabaseContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    #region 获取菜单列表

    public async Task<RequestResponseModel> GetBlogMenuList(BlogMenuSearchDTO searchDTO)
    {
        //sql
        var sql = @"
                SELECT
                    Id,
                    Code,
                    Name,
                    SuperiorId,
                    SuperiorName,
                    Order,
                    IsDelete,
                    CreateTime
                FROM
                    Department
                WHERE
                    IsDelete = 0
            ";

        // 构建查询条件
        var query = _context.Database.SqlQueryRaw<BlogMenuView>(sql)
            .AsQueryable().WhereIF(a => a.Code.Contains(searchDTO.Code), !string.IsNullOrEmpty(searchDTO.Code))
            .WhereIF(a => a.Name.Contains(searchDTO.Name), !string.IsNullOrEmpty(searchDTO.Name))
            .WhereIF(a => a.CreateTime > searchDTO.StartTime, searchDTO.StartTime != null)
            .WhereIF(a => a.CreateTime < searchDTO.EndTime, searchDTO.EndTime != null);

        // 获取分页数据
        var menuList = await query
            .OrderBy(a => a.Order)
            .Page(searchDTO.PageIndex, searchDTO.PageSize)
            .ToListAsync();

        // 获取总数
        var pageCount = await query.CountAsync();

        // 返回分页结果
        var pageResult = new PageResult<BlogMenuView>(menuList, pageCount);
        return RequestResponse.OK(pageResult, "查询成功");
    }

    #endregion

    #region 新增菜单

    public async Task<RequestResponseModel> AddBlogMenu(BlogMenuAddDTO addDTO)
    {
        // 检查编码是否已存在
        if (await _context.BlogMenu.AnyAsync(m => m.Code == addDTO.Code))
            return RequestResponse.ErrorRequest("菜单编码已存在");

        // 映射到实体模型
        var menu = _mapper.Map<BlogMenuModel>(addDTO);

        // 设置默认值
        menu.Id = Guid.NewGuid();
        menu.CreateTime = DateTime.Now;

        // 添加到数据库
        _context.BlogMenu.Add(menu);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(menu.Id, "新增成功");
    }

    #endregion

    #region 更新菜单

    public async Task<RequestResponseModel> PutBlogMenu(BlogMenuUpdateDTO updateDTO)
    {
        // 验证ID有效性
        var existingMenu = await Valid.ValidId(_context.BlogMenu, updateDTO.Id);
        if (existingMenu == null) return RequestResponse.ErrorRequest("菜单ID无效");

        // 更新实体数据
        _mapper.Map(updateDTO, existingMenu);

        // 保存到数据库
        _context.BlogMenu.Update(existingMenu);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(updateDTO.Id, "更新成功");
    }

    #endregion

    #region 删除菜单

    public async Task<RequestResponseModel> DeleteBlogMenu(SingleIdDTO deleteDTO)
    {
        // 验证ID有效性
        var menu = await Valid.ValidId(_context.BlogMenu, deleteDTO.Id);
        if (menu == null) return RequestResponse.ErrorRequest("菜单ID无效");

        // 执行删除
        _context.BlogMenu.Remove(menu);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(deleteDTO.Id, "删除成功");
    }

    #endregion
}